package com.redwood.report.net;

import android.util.Log;

import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetworkResponse;
import com.duowan.mobile.netroid.ParseError;
import com.duowan.mobile.netroid.Request;
import com.duowan.mobile.netroid.Response;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.redwood.report.entity.ServiceResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

/**
 * String网络请求
 *
 * @author supeng
 *         Created by  on 2016/9/7 17:23.
 */
public class SpSRequest extends Request<ServiceResult> {
    private Type rspCls;

    public SpSRequest(int method, String url, Listener<ServiceResult> listener, final Type rspCls) {
        super(method, url, listener);
        this.rspCls = rspCls;
    }

    public SpSRequest(String url, Listener<ServiceResult> listener, final Type rspCls) {
        this(Method.GET, url, listener, rspCls);

    }

    @Override
    protected Response<ServiceResult> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, response.charset);
            Log.i("supeng", "response:url=" + getUrl() + "  ||String=" + jsonString);
            JSONObject jsonObject = new JSONObject(jsonString);
            Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
            ServiceResult rsp = (ServiceResult) gson.fromJson(jsonObject.toString(), rspCls);
            return Response.success(rsp, response);
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}
